package com.yswy.common.utils.dingding;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.yswy.common.utils.redis.RedisUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DingUtil {
    @Autowired
    private RedisUtil redisUtil;
    @Value("${pagkename1}")
    private String pagekname1;

    @Value("${Ding.SECRET}")
    private String SECRET ;
    @Value("${Ding.accessToken}")
    private String accessToken ;
    private final String DING_URL = "https://oapi.dingtalk.com/robot/send?access_token=";

//    private static final String pagekname1 = "照片王";
//    private static final String SECRET = "SEC52195c4a712709b4621892f97613fa94c5ccf279aa05c8e0e0743a47f53875e5";
//    private static final String accessToken = "54b3f68c828efee6bba4e619f9dae80b8535d0b177047c606cbe50c5f943756d";
    private final String DingMsgNum = "ding_msg_mum" ;

    public static void main(String[] args) {
        DingUtil dingUtil = new DingUtil();
        dingUtil.sendMsg("test");
    }


    public void sendMsg(String message) {
        message = "----------------"+pagekname1+"----------------\n "+message;
        try {
            if (redisUtil.hasKey(DingMsgNum)){
                Integer num = Integer.parseInt(redisUtil.get(DingMsgNum));
                if (num >= 10){
                    return;
                }else {
                    num ++;
                    redisUtil.setForTimeMS(DingMsgNum ,num.toString() , 60*1000 );
                }
            }else {
                redisUtil.setForTimeMS(DingMsgNum ,"1" , 60*1000 );
            }

            //群机器人复制到的秘钥secret
            //获取系统时间戳
            Long timestamp = System.currentTimeMillis();
            //拼接
            String stringToSign = timestamp + "\n" + SECRET;
            //使用HmacSHA256算法计算签名
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SECRET.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            //进行Base64 encode 得到最后的sign，可以拼接进url里
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            //钉钉机器人地址（配置机器人的webhook）
            String dingUrl = DING_URL+accessToken + "&timestamp=" + timestamp + "&sign=" + sign;

            //是否通知所有人
            //通知具体人的手机号码列表
            List<String> mobileList = ListUtil.list(false);
            //钉钉机器人消息内容
            mobileList.add("18080455214");
            //组装请求内容
            String reqStr = buildReqStr(message, true, mobileList);
            //推送消息（http请求）
            HttpURLConnection urlConnection = (HttpURLConnection) new URL(dingUrl).openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            urlConnection.setDoOutput(true);
//            System.out.println(reqStr);
            urlConnection.getOutputStream().write(reqStr.getBytes(StandardCharsets.UTF_8));
            InputStream inputStream = urlConnection.getInputStream();
            String result = IoUtil.read( inputStream, StandardCharsets.UTF_8);
            inputStream.close();
            // String result = HttpClientUtil.sendPostDataByJson(sign, reqStr,"utf8");
            System.out.println("result == " + result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 组装请求报文
     *
     * @param content
     * @return
     */
    private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("content", content);
        //通知人
        Map<String, Object> atMap = new HashMap<>();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);

        return JSON.toJSONString(reqMap);
    }
}
